package net.maergaiyun.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.maergaiyun.component.SmsComponent;
import net.maergaiyun.constant.RedisKey;
import net.maergaiyun.enums.BizCodeEnum;
import net.maergaiyun.enums.SendCodeEnum;
import net.maergaiyun.service.NotifyService;
import net.maergaiyun.util.CheckUtil;
import net.maergaiyun.util.CommonUtil;
import net.maergaiyun.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {
    /**
     * 验证码有效期
     */
    private static final int CODE_EXPIRED = 60 * 1000 * 10;

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            long leftTime = CommonUtil.getCurrentTimestamp() - ttl;
            if (leftTime < 1000 * 60) {
                log.info("验证码发送过快, 时间间隔: {}", leftTime / 1000);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        String code = CommonUtil.getRandomCode(6);
        log.info("手机验证码: {}", code);
        String value = code + "_" + CommonUtil.getCurrentTimestamp();
        // 验证码存入redis
        redisTemplate.opsForValue().set(cacheKey, value, CODE_EXPIRED, TimeUnit.MILLISECONDS);

        if (CheckUtil.isEmail(to)) {
            //TODO 发送邮箱验证码
        } else {
//            smsComponent.send(to, code);
        }

        return JsonData.buildSuccess();
    }

    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if (cacheCode.equalsIgnoreCase(code)) {
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }

//    @Override
//    @Async("threadPoolTaskExecutor")
//    public void testSend() {
//        try {
//            TimeUnit.MILLISECONDS.sleep(200);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//
////        ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://api.vvhan.com/api/qr", String.class);
////        String body = responseEntity.getBody();
//        log.info("body");
//    }
}
